import os
try:
    from mako.template import Template
except ImportError:
    print('an error occured importing mako')

cwd = os.getcwd()

current_app = os.path.join(cwd,'applications',request.application)

about_template_path           = os.path.join(current_app,'static','plugin_plugin','about_template')
contribute_template_path      = os.path.join(current_app,'static','plugin_plugin','contribute_template')
controller_template_path      = os.path.join(current_app,'static','plugin_plugin','controller_template')
license_template_path         = os.path.join(current_app,'static','plugin_plugin','license_template')
model_template_path           = os.path.join(current_app,'static','plugin_plugin','model_template')
universal_cake_template_path  = os.path.join(current_app,'static','plugin_plugin','universal_cake_template')
voice_of_access_template_path = os.path.join(current_app,'static','plugin_plugin','voice_of_access_template')

auth.settings.on_failed_authorization = URL(r=request,f='failed_authorization',args=T('you need additional permissions to perform this action'))

def index():
    return dict(message="hello from plugin_plugin.py function index")

@auth.requires_login()
def site_user():
    return dict(message="hello from plugin_plugin.py function site_user")

@auth.requires_membership('config_plugin_plugin')    
def configure():
    return dict(message="hello from plugin_plugin.py function admin")

@auth.requires_membership('admin_plugin_plugin')
def admin():
    return dict(message="hello from plugin_plugin.py function admin")

def display_static():
    """
    Displays app_name/plugin_font_midnight/static/
    """
    file_name=request.args(0) or redirect(URL('index'))    
    file_path = os.path.join(cwd,'applications',request.application, 'static', 'plugin_plugin', file_name)
    if os.path.exists(file_path):
        content=open(file_path,'r').read()
        body = MARKMIN(content)
    else:
        body = MARKMIN('file not found')
    return dict(body=body)


def create_plugin():
    '''
    eventually we want to collect our user variables here and pass them to our create_plugin function
    '''
    form=FORM(TABLE(TR(T("Plugin prefix:"),INPUT(_type="text",_name="plugin_prefix",value="plugin",requires=IS_NOT_EMPTY())),
                        TR(T("Category:"),INPUT(_type="text",_name="plugin_category" ,value="font")),
                        TR(T("Suffix:"),INPUT(_type="text",_name="plugin_suffix",value="blackout",requires=IS_NOT_EMPTY())),
                        TR(T("Description"),TEXTAREA(_name="profile",value="describe your plugin here.")),
                        TR(T("Submit"),INPUT(_type="submit",_value=T("Submit")))))
    if form.accepts(request.vars, session):
        session.flash = 'form accepted'
#        redirect(URL('create_plugin'))
        plugin_category = plugin_name        =   ''
        spacer             =   '_'
        plugin_prefix      = request.vars.plugin_prefix   #  'plugin'
        plugin_category    = request.vars.plugin_category #  'uc'         # 'font'
        plugin_suffix      = request.vars.plugin_suffix   #'test001'    # 'blackout'
        if plugin_category == '':
            if 'plugin_plugin_debug' in globals():
                print('no plugin_category specified') 
            plugin_name = plugin_prefix + spacer + plugin_suffix
        else:
            if 'plugin_plugin_debug' in globals():
                print('plugin_category = %s') % (plugin_category)
            plugin_name = plugin_prefix + spacer + plugin_category + spacer + plugin_suffix
        context = dict(plugin_name=plugin_name)
        about_destination           = os.path.join(current_app,'static',     plugin_name,'about')
        contribute_destination      = os.path.join(current_app,'static',     plugin_name,'contribute')
        controller_destination      = os.path.join(current_app,'controllers',plugin_name + '.py')
        css_destination             = os.path.join(current_app,'static',     plugin_name,'css','__init__.py ')
        license_destination         = os.path.join(current_app,'static',     plugin_name,'license')
        model_destination           = os.path.join(current_app,'models',     plugin_name + '.py')
        module_destination          = os.path.join(current_app,'modules',    plugin_name,'__init__.py ')
        private_destination         = os.path.join(current_app,'private',    plugin_name,'__init__.py ')  
        universal_cake_destination  = os.path.join(current_app,'static',     plugin_name,'universal_cake')
        voice_of_access_destination = os.path.join(current_app,'static',     plugin_name,'voice_of_access')
        
        model_content = response.render(model_template_path,context)       
        ensure_file(model_destination, model_content)
        contribute_content = response.render(contribute_template_path,context)       
        ensure_file(contribute_destination, contribute_content)
        controller_content = response.render(controller_template_path,context)       
        ensure_file(controller_destination, controller_content)
        ensure_file(css_destination)
        ensure_file(module_destination)
        ensure_file(private_destination)    
        about_content = response.render(about_template_path,context)       
        ensure_file(about_destination, about_content)
        license_content = response.render(license_template_path,context)       
        ensure_file(license_destination, license_content)
        universal_cake_content = response.render(universal_cake_template_path,context)       
        ensure_file(universal_cake_destination, universal_cake_content)
        voice_of_access_content = response.render(voice_of_access_template_path,context)       
        ensure_file(voice_of_access_destination, voice_of_access_content)
        message = '''
        You ran the create_plugin plugin and it probably worked.
        If it did you should see a new menu item after refreshing your browser
        '''
        return dict(message=message)
    elif form.errors:
        response.flash="form is invalid"
    else:
        response.flash="please fill the form"
    return dict(form=form,vars=form.vars)

def create_set_plugin():
    plugin_name        =   ''
    spacer             =   '_'
    plugin_prefix      =   'plugin'
    plugin_category    =   'uc'         # 'font'
    plugin_suffix      =   'test001'    # 'blackout'
    plugin_name        =   plugin_prefix  +   spacer  +   plugin_category +  spacer  +   plugin_suffix
    model_destination       =   os.path.join(current_app,'models',plugin_name + '.py')
    controller_destination  =   os.path.join(current_app,'controllers',plugin_name + '.py')
    about_destination       =   os.path.join(current_app,'static',plugin_name,'about')
    license_destination     =   os.path.join(current_app,'static',plugin_name,'license')
    module_destination      =   os.path.join(current_app,'modules',plugin_name,'__init__.py ')
    private_destination     =   os.path.join(current_app,'private',plugin_name,'__init__.py ')      
    model_plugin_plugin_py_template = Template(filename=model_template_path)
    model_plugin_plugin_py_content  = model_plugin_plugin_py_template.render(plugin_name=plugin_name)
    ensure_file(model_destination, content      = model_plugin_plugin_py_content)
    ## controller.py - models/plugin_plugin.py
    controller_py_template = Template(filename=controller_template_path)
    controller_py_content = controller_py_template.render(plugin_name=plugin_name)
    ensure_file(controller_destination,content=controller_py_content)
    ensure_file(module_destination)
    ensure_file(private_destination)    
    about_template = Template(filename=about_template_path)
    about_content = about_template.render(plugin_name=plugin_name)
    ensure_file(about_destination,content=about_content)
    license_template = Template(filename=license_template_path)
    license_content = license_template.render(plugin_name=plugin_name)
    ensure_file(license_destination,content=license_content)    
    message = '''
    You ran the create_plugin plugin and it probably worked.
    If it did you should see a new menu item after refreshing your browser
    '''
    return dict(message=message)
    
def failed_authorization():
    if len(request.args):
        message=str(request.args[0])
    else:
        message=T("not authorized")
    return dict(message=message)
